package com.guosen.zebra.framework.starter.startup.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Zebra 信息指示器，用于向 /actuator/info 端点输出自定义 Zebra 信息
 */
@Slf4j
public class ZebraInfoContributor implements InfoContributor {

    /**
     * Zebra信息<br/>
     * 信息不会动态变化，使用成员变量存储起来，避免每次请求都重新计算。
     */
    private final Map<String, String> zebraInfo = new HashMap<>();

    /**
     * 未知版本
     */
    private static final String UNKNOWN_VERSION = "unknown";

    /**
     * 是否已初始化: false未初始化, true : 已初始化
     */
    private volatile boolean initialized = false;


    @Override
    public void contribute(Info.Builder builder) {
        // double check
        if (!initialized) {
            synchronized (this) {
                if (!initialized) {
                    zebraInfo.put("version", getZebraVersion());
                    initialized = true;
                }
            }
        }

        builder.withDetail("zebra", zebraInfo);
    }

    private String getZebraVersion() {
        // 获取Zebra框架版本
        String version = UNKNOWN_VERSION;
        Properties pomProperties = new Properties();
        try {
            try (InputStream pomStream = ZebraInfoContributor.class.getResourceAsStream(
                    "/META-INF/maven/com.guosen.zebra.framework/zebra-startup-spring-boot-starter/pom.properties"
            )) {
                pomProperties.load(pomStream);
                version = pomProperties.getProperty("version", UNKNOWN_VERSION);
            }
        } catch (Exception e) {
            log.error("Failed to read Zebra version from pom.properties", e);
        }

        return version;
    }
}
